<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController
{
    /**
     * 后台统一上传
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|file',
            'type' => 'required|string|in:config,image,avatar',
        ]);

        $originName = $request->file('file')->getClientOriginalName();
        $type = $request->type;
        switch ($type) {
            case 'config': // 配置文件原始名称直传
                $disk = Storage::disk('oss');
                $path = 'config';
                $filepath = $disk->putFileAs($path, $request->file('file'), $originName);
                $url = $disk->url($filepath);
                break;
            case 'image':
                $disk = Storage::disk('oss');
                $path = 'uploads/images/' . date('Ym');
                $filepath = $disk->put($path, $request->file('file'));
                $url = getCdnUrl($filepath);
                break;
            default: // 默认使用本地
                $disk = Storage::disk('uploads');
                $path = $type .'/'. date('Ym');
                $filepath = $disk->put($path, $request->file('file'));
                $url = $disk->url($filepath);
                break;
        }
        // 本地开发
        // if (config('app.env') === 'local') {
        //     $disk = Storage::disk('uploads');
        //     $path = $type .'/'. date('Ym');
        // }

        return compact('url', 'filepath');
    }
}
